/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pt.iasd.youthshelter.pathfinder.wizards;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;
import org.openide.DialogDescriptor;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.WizardDescriptor;
import org.openide.util.Lookup;
import pt.iasd.youthshelter.datamodel.PathfinderRole;
import pt.iasd.youthshelter.datamodel.Role;
import pt.iasd.youthshelter.datamodel.service.RoleController;

/**
 *
 * @author Rui
 */
public class RoleTablePanel extends javax.swing.JPanel {
    private static final ResourceBundle bundle = java.util.ResourceBundle.getBundle("pt/iasd/youthshelter/pathfinder/Bundle");
    
    /* Logging object. */
    private Logger logger = Logger.getLogger(this.getClass().getName());
    
    private List<Role> roles = loadRoleTableData();
    
    private Set<Integer> editedRoles = new HashSet<Integer>();
    
    private Set<Integer> removedRoles = new HashSet<Integer>();

    /**
     * Creates new form RoleTablePanel
     */
    public RoleTablePanel() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        AddButton = new javax.swing.JButton();
        EditButton = new javax.swing.JButton();
        RemoveButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        RoleTable = new javax.swing.JTable();

        setPreferredSize(new java.awt.Dimension(700, 300));

        org.openide.awt.Mnemonics.setLocalizedText(AddButton, bundle.getString("Buttons.Add"));
        AddButton.setMaximumSize(new java.awt.Dimension(100, 23));
        AddButton.setMinimumSize(new java.awt.Dimension(100, 23));
        AddButton.setPreferredSize(new java.awt.Dimension(100, 23));
        AddButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AddButtonActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(EditButton, bundle.getString("Buttons.Edit"));
        EditButton.setMaximumSize(new java.awt.Dimension(100, 23));
        EditButton.setMinimumSize(new java.awt.Dimension(100, 23));
        EditButton.setPreferredSize(new java.awt.Dimension(100, 23));
        EditButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                EditButtonActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(RemoveButton, bundle.getString("Buttons.Remove"));
        RemoveButton.setMaximumSize(new java.awt.Dimension(100, 23));
        RemoveButton.setMinimumSize(new java.awt.Dimension(100, 23));
        RemoveButton.setPreferredSize(new java.awt.Dimension(100, 23));
        RemoveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                RemoveButtonActionPerformed(evt);
            }
        });

        RoleTable.setModel(buildTableModel());
        RoleTable.removeColumn(RoleTable.getColumn(RoleTable.getColumnName(0)));
        EditButton.setEnabled(false);
        RemoveButton.setEnabled(false);
        RoleTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                RoleTableMousePressed(evt);
            }
        });
        jScrollPane1.setViewportView(RoleTable);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 584, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(AddButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(EditButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(RemoveButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(AddButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(EditButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(RemoveButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(208, Short.MAX_VALUE))
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents

    private void AddButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AddButtonActionPerformed
        List<WizardDescriptor.Panel<WizardDescriptor>> panels = new ArrayList<WizardDescriptor.Panel<WizardDescriptor>>();
        panels.add(new AddRoleWizardPanel());
        WizardDescriptor wiz = new WizardDescriptor(new WizardDescriptor.ArrayIterator<WizardDescriptor>(panels));
        wiz.setTitleFormat(new MessageFormat("{0}"));
        wiz.setTitle(bundle.getString("Role.Title.Add"));
        List<String> roleNames = new ArrayList<String>();
        if(roles != null && !roles.isEmpty()) {
            for(Role role : roles) {
                roleNames.add(role.getName());
            }
        }
        wiz.putProperty(WizardKeys.PROP_LIST, roleNames);
        if (DialogDisplayer.getDefault().notify(wiz) == WizardDescriptor.FINISH_OPTION) {
            String name = (String)wiz.getProperty(WizardKeys.PROP_NAME);
            roles.add(new Role(name));
            setTable();
        }
    }//GEN-LAST:event_AddButtonActionPerformed

    private void EditButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EditButtonActionPerformed
        int selectedRow = RoleTable.getSelectedRow();
        List<WizardDescriptor.Panel<WizardDescriptor>> panels = new ArrayList<WizardDescriptor.Panel<WizardDescriptor>>();
        panels.add(new EditRoleWizardPanel());
        WizardDescriptor wiz = new WizardDescriptor(new WizardDescriptor.ArrayIterator<WizardDescriptor>(panels));
        wiz.setTitleFormat(new MessageFormat("{0}"));
        wiz.setTitle(bundle.getString("Role.Title.Edit"));
        List<String> roleNames = new ArrayList<String>();
        if(roles != null && !roles.isEmpty()) {
            for(Role role : roles) {
                roleNames.add(role.getName());
            }
        }
        Role role = roles.get(selectedRow);
        wiz.putProperty(WizardKeys.PROP_LIST, roleNames);
        wiz.putProperty(WizardKeys.PROP_NAME, role.getName());
        if (DialogDisplayer.getDefault().notify(wiz) == WizardDescriptor.FINISH_OPTION) {
            String name = (String)wiz.getProperty(WizardKeys.PROP_NAME);
            role.setName(name);
            if(roles.get(selectedRow).getId() != null) {
                editedRoles.add(role.getId());
            }
            setTable();
        }
    }//GEN-LAST:event_EditButtonActionPerformed

    private void RemoveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RemoveButtonActionPerformed
        int selectedRow = RoleTable.getSelectedRow();
        NotifyDescriptor dialog = new NotifyDescriptor(
                String.format(bundle.getString("Role.Confirmation.Remove"),
                        roles.get(selectedRow).getName()),
                bundle.getString("Role.Title.Remove"), NotifyDescriptor.OK_CANCEL_OPTION,
                NotifyDescriptor.WARNING_MESSAGE, null, null);
        if(DialogDisplayer.getDefault().notify(dialog) == DialogDescriptor.OK_OPTION) {
            if(roles.get(selectedRow).getId() != null) {
                removedRoles.add(roles.get(selectedRow).getId());
            }
            roles.remove(selectedRow);
            setTable();
        }
    }//GEN-LAST:event_RemoveButtonActionPerformed

    private void RoleTableMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_RoleTableMousePressed
        int selectedRow = RoleTable.getSelectedRow();
        if(selectedRow != -1) {
            EditButton.setEnabled(true);
            List<PathfinderRole> pathfinders = roles.get(selectedRow).getPathfinderRoleList();
            RemoveButton.setEnabled(pathfinders == null || pathfinders.isEmpty());
        } else {
            EditButton.setEnabled(false);
            RemoveButton.setEnabled(false);
        }
    }//GEN-LAST:event_RoleTableMousePressed

    public List<Role> getRoles() {
        return roles;
    }

    public Set<Integer> getEditedRoles() {
        return editedRoles;
    }

    public Set<Integer> getRemovedRoles() {
        return removedRoles;
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton AddButton;
    private javax.swing.JButton EditButton;
    private javax.swing.JButton RemoveButton;
    private javax.swing.JTable RoleTable;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables

    // <editor-fold defaultstate="collapsed" desc="Table Data Code">
    private List<Role> loadRoleTableData() {
        RoleController controller = Lookup.getDefault().lookup(RoleController.class);
        if(controller != null) {
            try{
                return controller.findRoleEntities();
            } catch(Exception ex) {
                logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
            }
        }
        return null;
    }
    
    private DefaultTableModel buildTableModel(){
        Object[][] data;
        String[] headers = new String[]{
            bundle.getString("TableHeaders.Id"),
            bundle.getString("TableHeaders.Name")};
        if(roles == null || roles.isEmpty()) {
            data = new Object[][]{};
        } else {
            data = new Object[roles.size()][Role.class.getDeclaredFields().length - 2];
            int i = 0;
            for(Role role : roles) {
                data[i][0] = role.getId();
                data[i][1] = role.getName();
                ++i;
            }
        }
        DefaultTableModel tablemodel = new DefaultTableModel(data, headers){
            Class[] types = new Class[]{java.lang.Integer.class, java.lang.String.class};
            boolean[] canEdit = new boolean[]{false, false};

            @Override
            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            @Override
            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        };
        return tablemodel;
    }
    
    private void setTable() {
        RoleTable.setModel(buildTableModel());
        RoleTable.removeColumn(RoleTable.getColumn(RoleTable.getColumnName(0)));
        EditButton.setEnabled(false);
        RemoveButton.setEnabled(false);
    }// </editor-fold>
}
